//
//  RMMPersonSetViewController.m
//  Romomo
//
//  Created by puman on 2016/10/18.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMPersonSetViewController.h"
#import "RMMMineSetTableViewCell.h"
#import "RMMMineSetHeadTableViewCell.h"
#import "RMMPersonNextViewController.h"
#import "RMMSelcetPickerView.h"
#import "RMMLocationModel.h"

@interface RMMPersonSetViewController ()<UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPickerViewDelegate,UIPickerViewDataSource>

@end

@implementation RMMPersonSetViewController
{
    UITableView *_tableView;
    UIImage *_photoImage;
    NSArray *_locationArray;
    NSArray *_lcArray;
    UIBarButtonItem *_item;
    UIImagePickerController *_imagePickerController;
    RMMSelcetPickerView *_selcetPickerView;
    NSString *_name;
    NSInteger _number;
    NSInteger _row;
    NSInteger _shenRow;
    NSInteger _shiRow;
    NSInteger _quRow;
    NSString *_date;
    NSString *_gender;
    NSString *_city;
    NSString *_shenCode;
    NSString *_shiCode;
    NSString *_regionCode;
    NSDictionary *_dataDic;
    NSString *_pickerViewType;
}
- (void)dealloc{
    NS_REM(@"PERSONREFRESH", nil);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kCColor;
    self.navigationItem.title = @"编辑资料";
    [self addVies];
    [self addRinghtItem];
    [self getDataWith:[RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]]];
    NS_ADD(refresh:, @"PERSONREFRESH", nil);
    // Do any additional setup after loading the view.
}
- (void)refresh:(NSNotification *)notification{
    NSDictionary *dic = [notification userInfo];
    [self getDataWith:dic[@"cust_id"]];
}
- (void)addVies{
    _row = 0;
    _shenRow = 0;
    _shiRow = 0;
    _quRow = 0;
    _gender = @" ";
    _name = @" ";
    _date = @" ";
    _city = @" ";
    [self getLocationData];
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 0)];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 48 + 54 * 5 + 80) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.scrollEnabled = NO;
    _tableView.tableFooterView = footView;
    [_tableView registerClass:[RMMMineSetTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [_tableView registerClass:[RMMMineSetHeadTableViewCell class] forCellReuseIdentifier:@"PhotoCell"];
    [self.view addSubview:_tableView];
    
    _selcetPickerView = [[RMMSelcetPickerView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    BUTTON_S(_selcetPickerView.rihthBut, doneButClick);
    _selcetPickerView.pickerView.dataSource = self;
    _selcetPickerView.pickerView.delegate = self;
    _selcetPickerView.hidden = YES;
    [self.view addSubview:_selcetPickerView];
}
- (void)getDataWith:(NSString *)string{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"cust_id"] = string;
    NSString *url = UserInfo;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            _dataDic = [RMMFileManager setValueForDic:dataDic[@"data"]];
            _gender = [RMMFileManager retrunObjWith:_dataDic[@"GENDER"]];
            _date = [RMMFileManager retrunObjWith:_dataDic[@"BIRTHDAY"]];
            _city = [RMMFileManager retrunObjWith:_dataDic[@"CITY_NAME"]];
            _name = [RMMFileManager retrunObjWith:_dataDic[@"NAME"]];
        }
        [_tableView reloadData];
    } error:^(NSError *errors) {
        
    } view:self.view];

}
- (void)addRinghtItem{
    _item = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:(UIBarButtonItemStylePlain) target:self action:@selector(itemClcik)];
    _item.tintColor = kBasicColor;
}
// 提交修改资料
- (void)itemClcik{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"cust_id"] = _dataDic[@"CUST_ID"];
    parDic[@"name"] = _name;
    parDic[@"birthday"] = _date;
    parDic[@"province"] = _shenCode;
    parDic[@"city"] = _shiCode;
    parDic[@"regiion"] = _regionCode;
    parDic[@"gender"] = _gender;
    NSString *url = UpdataCustUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [MMProgressHUD show];
            self.navigationItem.rightBarButtonItem = nil;
            [MMProgressHUD dismissWithSuccess:@"修改成功!" title:nil afterDelay:1.0];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
    } error:^(NSError *errors) {
        
    } view:self.view];

}
// 判断是否修改
- (void)checkChanged{
    if ([_gender isEqualToString:[RMMFileManager retrunObjWith:_dataDic[@"GENDER"]]] && [_date isEqualToString:[RMMFileManager retrunObjWith:_dataDic[@"BIRTHDAY"]]] && [_city isEqualToString:[RMMFileManager retrunObjWith:_dataDic[@"CITY_NAME"]]] && [_name isEqualToString:[RMMFileManager retrunObjWith:_dataDic[@"NAME"]]]) {
        self.navigationItem.rightBarButtonItem = nil;
    } else {
        self.navigationItem.rightBarButtonItem = _item;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 4;
    } else {
        return 1;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 80;
    } else {
        return 54;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 16;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 16)];
    view.backgroundColor = kCColor;
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        RMMMineSetHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PhotoCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.titleName.text = @"头像";
        cell.ioc_url = [RMMFileManager retrunObjWith:[NSString stringWithFormat:@"%@%@",kBaseUrl,_dataDic[@"IMAGE_URL"]]];
        return cell;
    } else {
        RMMMineSetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        cell.tag = 2 +  indexPath.row;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if (indexPath.section == 1) {
            if (indexPath.row == 0) {
                cell.titleName.text = @"昵称";
                cell.content.text = _name.length == 0 ? @"未知" : _name;
            } else if (indexPath.row == 1) {
                cell.titleName.text = @"性别";
                cell.content.text = _gender.length == 0 ? @"未知" : _gender;
            } else if (indexPath.row == 2){
                cell.titleName.text = @"出生日期";
                cell.content.text = _date.length == 0 ? @"未知" : _date;
            } else {
                cell.titleName.text = @"所在城市";
                cell.content.text = _city.length == 0 ? @"未知" : _city;
            }
        } else {

            cell.tag = 6 + indexPath.row;
            cell.titleName.text = @"登录密码";
            if ([_dataDic[@"IS_PWD"] isEqualToString:@"1"]) {
                cell.content.text =  @"已设置";
            } else {
                cell.content.text =  @"未设置";
            }
        }
        return cell;
    }
 }
// 完成
- (void)doneButClick{
    if ([_pickerViewType isEqualToString:@"date"]) {
        if (!_date.length) {
            _date = [RMMFileManager getNowTimeWithFormatterString:@"yyyy-MM-dd"];
        } else {
            if ([_date compare:[RMMFileManager getNowTimeWithFormatterString:@"yyyy-MM-dd"]] == NSOrderedDescending) {
                [RMMFileManager MBProgressWith:@"选择时间不能大于现在时间!" onView:self.view];
                return;
            }
        }
    } else {
        NSDictionary *dic = _locationArray[_shenRow];
        _shenCode = dic[@"CODE"];
        NSArray *array = dic[@"CITY"];
        NSDictionary *d = array[_shiRow];
        _shiCode = d[@"CODE"];
        _city = d[@"NAME"];
        NSArray *arrayQu = d[@"REGION"];
        NSDictionary *newDic = arrayQu[_quRow];
        _regionCode = newDic[@"CODE"];
    }
    [_tableView reloadData];
    [UIView animateWithDuration:kInterval animations:^{
        _selcetPickerView.view.frame = CGRectMake(0, kScreenHeight , kScreenWideth, 249);
        _selcetPickerView.backView.alpha = 0.0;
    } completion:^(BOOL finished) {
        _selcetPickerView.hidden = YES;
    }];
    [self checkChanged];

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        [self addAlertController];
    } else if (indexPath.section == 1) {
        RMMPersonNextViewController *nextVC = [[RMMPersonNextViewController alloc] init];
        if (indexPath.row == 0) {
            nextVC.titleName = @"修改昵称";
            nextVC.name = _name;
            nextVC.passwordBlcok = ^void(NSString *string) {
                _name = string;
                self.navigationItem.rightBarButtonItem = _item;
                [_tableView reloadData];
            };
            [self.navigationController pushViewController:nextVC animated:YES];
        } else if (indexPath.row == 1){
            _number = 1;
            [self addGenderAlertController];
        } else if (indexPath.row == 2) {
            [_selcetPickerView.datePicker addTarget:self action:@selector(getDate:) forControlEvents:(UIControlEventValueChanged)];
            _selcetPickerView.hidden = NO;
            _selcetPickerView.type = @"date";
            _pickerViewType = @"date";
            [UIView animateWithDuration:kInterval animations:^{
                _selcetPickerView.view.frame = CGRectMake(0, kScreenHeight - 64 - 249, kScreenWideth, 249);
                _selcetPickerView.backView.alpha = 1.0;
            } completion:^(BOOL finished) {
                
            }];
        } else {
            if (_locationArray.count) {
                _selcetPickerView.hidden = NO;
                _selcetPickerView.type = @"location";
                [UIView animateWithDuration:kInterval animations:^{
                    _selcetPickerView.view.frame = CGRectMake(0, kScreenHeight - 64 - 249, kScreenWideth, 249);
                    _selcetPickerView.backView.alpha = 1.0;
                } completion:^(BOOL finished) {
                }];
            } else {
                [self getLocationData];
            }

        }
    } else {
        RMMPersonNextViewController *nextVC = [[RMMPersonNextViewController alloc] init];
        nextVC.passwordBlcok = ^void(NSString *str){
            [self getDataWith:_dataDic[@"CUST_ID"]];
        };
        NSString *string = [RMMFileManager retrunObjWith:_dataDic[@"IS_PWD"]];
        if ([string isEqualToString:@"1"]) {
            nextVC.titleName = @"修改密码";
        } else {
            nextVC.titleName = @"设置登录密码";
        }
        [self.navigationController pushViewController:nextVC animated:YES];
    }
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return _locationArray.count;
    } else if (component == 1) {
        NSDictionary *dic = _locationArray[_shenRow];
        NSArray *array = dic[@"CITY"];

        return array.count;
    } else {
        NSDictionary *dic = _locationArray[_shenRow];
        NSArray *array = dic[@"CITY"];
        NSDictionary *d = array[_shiRow];
        NSArray *arrayQu = d[@"REGION"];
        return arrayQu.count;
    }
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (_locationArray.count) {
        if (component == 0) {
            NSDictionary *dic = _locationArray[row];
            return dic[@"NAME"];
        } else if(component == 1){
            NSDictionary *dic = _locationArray[_shenRow];
            NSArray *array = dic[@"CITY"];
            NSDictionary *subDic = array[row];
            return subDic[@"NAME"];
        } else {
            NSDictionary *dic = _locationArray[_shenRow];
            NSArray *array = dic[@"CITY"];
            NSDictionary *subDic = array[_shiRow];
            NSArray *subArray = subDic[@"REGION"];
            NSDictionary *d = subArray[row];
            return d[@"NAME"];
        }
    }
    return @"";
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (component == 0) {
        _shenRow = row;
        _shiRow = 0;
        _quRow = 0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [pickerView selectRow:0 inComponent:2 animated:YES];
        });
    } else if (component == 1){
        _shiRow = row;
        _quRow = 0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [pickerView selectRow:0 inComponent:2 animated:YES];
        });
    } else {
        _quRow = row;
    }
    [_selcetPickerView.pickerView reloadAllComponents];
}
- (void)getLocationData{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"code"] = @"1";
    NSString *url = LocationDataUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSArray *array = dataDic[@"data"];
            _locationArray = array;
            [[RMMFileManager shareHandle] saveVale:array forKey:@"LOCATIONARRAY"];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_selcetPickerView.pickerView reloadAllComponents];
    } error:^(NSError *errors) {
        
    } view:self.view];
}
- (void)addGenderAlertController{
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"选择您的性别" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *actionA = [UIAlertAction actionWithTitle:@"男" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        _gender = @"男";
        [self checkChanged];
        [_tableView  reloadData];
    }];
    UIAlertAction *actionB = [UIAlertAction actionWithTitle:@"女" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        _gender = @"女";
        [self checkChanged];
        [_tableView  reloadData];
    }];
    UIAlertAction *actionC = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertC addAction:actionA];
    [alertC addAction:actionB];
    [alertC addAction:actionC];
    [self presentViewController:alertC animated:YES completion:nil];
}
// 得到时间
- (void)getDate:(UIDatePicker *)picker{
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:@"yyyy-MM-dd"];
    _date = [outputFormatter stringFromDate:picker.date];
}

- (void)addAlertController{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"设置头像" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *actionA = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        // 相册
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }];
    UIAlertAction *actionB = [UIAlertAction actionWithTitle:@"照相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
       _imagePickerController = [[UIImagePickerController alloc] init];
        // 支持的 类型  为 相机
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        // 设置  相机 支持的功能 (拍照,视频)(注意: 转化类型~)
        _imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
        [self presentViewController:_imagePickerController animated:YES completion:nil];

    }];
    UIAlertAction *actionC = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:actionA];
    [alertController addAction:actionB];
    [alertController addAction:actionC];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    // 压缩图片
    _photoImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(250, 250)];
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"cust_id"] = _dataDic[@"CUST_ID"];
    parDic[@"ImageData"] = [UIImageJPEGRepresentation(_photoImage, 1.0f) base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    NSString *url = updataImage;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:POST finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NS_POST(@"UPDATEMINEDATA", nil, nil);
            [self getDataWith:[RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]]];
            [MMProgressHUD show];
            [MMProgressHUD dismissWithSuccess:@"头像上传成功!" title:nil afterDelay:1.0];
        }
        [_tableView reloadData];
    } error:^(NSError *errors) {
        
    } view:self.view];
}
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
